package com.woa;

import static org.red5.server.api.ScopeUtils.getScopeService;

import java.awt.Toolkit;
import java.util.Timer;
import java.util.TimerTask;

import org.red5.server.api.so.ISharedObject;
import org.red5.server.api.so.ISharedObjectService;
import org.red5.server.so.SharedObjectService;



import world.AntWorld;

public class MyTimer {
	  Toolkit toolkit;
	  Timer timer;
	  public Integer worldtime = 0;
	  AntWorld world;
	  public ISharedObject so;

	  public void create_tempo()
	  {
		  
			if (world.appli.appScope != null)
			{				
		      ISharedObjectService service = (ISharedObjectService) getScopeService(
		    		  world.appli.appScope,
		              ISharedObjectService.class,
		              SharedObjectService.class,
		              false
		        );				
				
		        service.createSharedObject(world.appli.appScope, "tempo", false);
				so = service.getSharedObject(world.appli.appScope, "tempo", false);	
				world.log.debug("timer shared object setup");	
			    so.setAttribute("time", worldtime);
			    world.log.debug("timer shared object start to " + so.getAttribute("time").toString());
			}
			else
			{
				world.log.debug("app scope is null");	
			}
		    
	  }
	  
	  public MyTimer(AntWorld _world) 
	  {
		world = _world;
		world.log.debug("timer is starting");
	    toolkit = Toolkit.getDefaultToolkit();
	    timer = new Timer();
	    timer.schedule(new RemindTask(), 0, //initial delay
	        1 * 1000); //subsequent rate
	    this.create_tempo();
	  }	

	  class RemindTask extends TimerTask {

	    public void run() {
	    	worldtime++;
	    	try 
	    	{
		    	world.life();  	
		    	world.antBox.m_world.step(1.0f / 30.0f, 10);
		    	so.beginUpdate();
		    	Boolean b = so.setAttribute("time", worldtime);
		    	so.endUpdate();
		    	//world.woal.woaobject_update();
		    	world.log.debug(b.toString() + " new step :" + so.getAttribute("time").toString());
		    	//world.woal.woaobject_update();
		    	//so.release();
	    	}
	    	catch (Exception e)
	    	{
	    		world.log.debug("Timer Failure under run : " + e.getLocalizedMessage());
	    		e.printStackTrace();
	    	}
	    }
	  }


	}
